package com.rambler.gateway.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;

/**
 * 全局跨域配置
 */
@Configuration
public class CorsConfig {

    @Value("${spring.cors.allowed-origins:*}")
    private String allowedOrigins;

    @Value("${spring.cors.allowed-headers:*}")
    private String allowedHeaders;

    @Value("${spring.cors.allowed-methods:*}")
    private String allowedMethods;

    @Value("${spring.cors.allow-credentials:true}")
    private Boolean allowCredentials;

    @Value("${spring.cors.pattern:/**}")
    private String pattern;

    @Bean
    public CorsWebFilter corsWebFilter() {
        CorsConfiguration config = new CorsConfiguration();
        // 从配置文件中读取允许的源
        config.addAllowedOriginPattern(allowedOrigins);
        // 从配置文件中读取允许的请求头
        config.addAllowedHeader(allowedHeaders);
        // 从配置文件中读取允许的请求方法
        config.addAllowedMethod(allowedMethods);
        // 从配置文件中读取是否允许携带认证信息
        config.setAllowCredentials(allowCredentials);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        // 从配置文件中读取CORS配置的应用路径
        source.registerCorsConfiguration(pattern, config);

        return new CorsWebFilter(source);
    }
}